<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if(!class_exists('Api_football_game')){
    class Api_football_game extends CI_Controller {

        protected $_action = '';

        protected $_distance = 325;

        public function __construct(){
            parent::__construct();
            $this->load->model('Apilogmodel','m_api_log');
            $this->load->model('Usermodel','m_user');
            $this->load->model('Appmodel','m_app');
            $this->load->model('Footballgamecustomermodel','m_customer');
            $this->load->model('configmodel','m_config');
            $this->load->database();
        }

        public function __destruct() {
            // $this->session->unset_userdata($this->_action);
            // //api开头的不存
            if(is_string($this->uri->rsegments[2]) && stripos($this->uri->rsegments[2], 'api') === 0) {
            	$this->db->close();
                return;
            }
            $customer = $this->session->userdata('football_game_customer');
            $info = $this->input->post();
            $result = $this->response->getResult();
            if(isset($info['nickname'])) {
                $info['nickname'] = remove_emoji($info['nickname']);
                // var_dump($info['nickname']);
                return;
            }
            @$this->m_api_log->createApiLog(array(
                'ip_address' => $this->input->ip_address(),
                'customer_id' => empty($customer) ? 0 :  $customer['customer_id'],
                'request_uri' => $_SERVER['REQUEST_URI'],
                'post_data' => json_encode($info,JSON_UNESCAPED_UNICODE),
                'result_data' => json_encode($result,JSON_UNESCAPED_UNICODE),
                'api_log_time_create' => NOW,
                'ua' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
                // 'terminal' => TERMINAL_WEIXIN,
            ));

            $this->db->close();
        }


        public function initCustomer() {
            $this->validate->setRule('openid','string');
            $this->validate->setRule('openid','message',$this->lang->line('error_parameter'));
            // $this->validate->setRule('openid_md5','string');
            // $this->validate->setRule('openid_md5','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('nickname','string');
            $this->validate->setRule('nickname','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('sex','integer');
            $this->validate->setRule('sex','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('province','string');
            $this->validate->setRule('province','notnull',false);
            $this->validate->setRule('province','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('city','string');
            $this->validate->setRule('city','notnull',false);
            $this->validate->setRule('city','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('country','string');
            $this->validate->setRule('country','notnull',false);
            $this->validate->setRule('country','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('headimgurl','string');
            $this->validate->setRule('headimgurl','notnull',false);
            $this->validate->setRule('headimgurl','message',$this->lang->line('error_parameter'));
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            // if(md5($info['openid'].FREEDOM_WAR_SALT) != $info['openid_md5']) {
            //     $this->response->setDetail('请勿恶意访问!');
            //     $this->response->responseExit();
            // }
            // unset($info['openid_md5']);


            
            $info['nickname'] = urlencode($info['nickname']);

            $customer = $this->m_customer->getCustomerByOpenid($info['openid']);
            if(empty($customer)) {
                $info['customer_time_create'] = NOW;
                $customer_id = $this->m_customer->createCustomer($info);
                if($customer_id == 0) {
                    $this->response->setDetail('初始化用户失败！请刷新页面！');
                    $this->response->responseExit();
                }
                $customer = $this->m_customer->getCustomer($customer_id);
            } else if($customer['nickname'] != $info['nickname'] || $customer['headimgurl'] != $info['headimgurl']){
                $info['customer_id'] = $customer['customer_id'];
                $this->m_customer->editCustomer($info);
                $customer = $this->m_customer->getCustomer($info['customer_id']);
            }
            $customer['nickname'] = urldecode($customer['nickname']);

            $this->session->set_userdata('football_game_customer',$customer);

            

            $this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->setAddon(array(
                'customer' => $customer,
            ));
            $this->response->responseExit();
        }

        public function submitScore() {
            $customer = $this->session->userdata('football_game_customer');
            if(empty($customer)) {
                $this->response->setDetail('初始化用户失败！请刷新页面重试！');
                $this->response->responseExit();
            }


            $this->validate->setRule('game_score','integer');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if($info['game_score'] < 170 || $info['game_score'] > 400) {
                $this->response->setDetail('成绩错误!');
                $this->response->responseExit();
            }

            $this->m_customer->createHistory(array(
            	'customer_id' => $customer['customer_id'],
            	'game_score' => $info['game_score'],
            	'history_time_create' => NOW,
            ));

            // if($info['game_score'] > $customer['game_max_score']) {
            	$this->m_customer->editCustomer(array(
            		'customer_id' => $customer['customer_id'],
            		'game_max_score' => $info['game_score'],
            		'customer_max_score_time_create' => NOW,
            	));
            // }

            $this->m_customer->updateCustomerGameCount($customer['customer_id']);

            $customer = $this->m_customer->getCustomer($customer['customer_id']);
            $customer['nickname'] = urldecode($customer['nickname']);

            list($list,$count) = $this->m_customer->getCustomerListSection(array(
                'where' => array(
                    'game_max_score >=' => $customer['game_max_score'],
                    // 'customer_max_score_time_create <' => $customer['customer_max_score_time_create'],
                ),
                'select' => 'customer_id,game_max_score,customer_max_score_time_create'
            ));
            foreach ($list as $key => $value) {
                if($value['game_max_score'] == $customer['game_max_score'] && $value['customer_max_score_time_create'] < $customer['customer_max_score_time_create']) {
                    unset($list[$key]);
                }
            }

            $this->session->set_userdata('football_game_customer',$customer);
            $this->response->setSuccess();
            $this->response->setAddon(array(
                'sort' => count($list),
                'game_max_score' => $customer['game_max_score'],
            ));
            $this->response->setDetail('提交成功!');
            $this->response->responseExit();
        }

        public function getScoreList() {
        	$customer = $this->session->userdata('football_game_customer');
            if(empty($customer)) {
                $this->response->setDetail('初始化用户失败！请刷新页面重试！');
                $this->response->responseExit();
            }

            list($list,$count) = $this->m_customer->getCustomerListSection(array(
            	'pagination' => array('start' => 0, 'limit' => 20),
            	'order_by' => array('game_max_score' => 'DESC','customer_max_score_time_create' => 'ASC'),
            	'where' => array(
            		'game_max_score >=' => '170',
            	),
            	'select' => 'nickname,game_max_score'
            ));

            foreach ($list as $key => $value) {
            	$list[$key]['nickname'] = urldecode($value['nickname']);
            }

            $this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->setItems($list);
            $this->response->responseExit();
        }

    }
    
}